package com.lzw.utils;

import org.apache.commons.lang.StringUtils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Enumeration;

/**
 * 获取本机IP地址
 *
 * @author liuzw
 * @date 2024/6/17
 */
public class LocalIpUtil {

    // 刷新间隔 2分钟
    private static final Long refreshTime = 2 * 60 * 1000L;
    private static String Ipv4;
    private static String Ipv6;
    private static Long lastRefreshTime = -1L;

    private static void init() {
        try {
            if (lastRefreshTime + refreshTime > LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() && StringUtils.isNotBlank(Ipv4) && StringUtils.isNotBlank(Ipv6)) {
                return;
            }
            lastRefreshTime = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface network = enumeration.nextElement();
                if (network.isVirtual() || !network.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = network.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        // 非内网地址，并且是IPv4
                        Ipv4 = address.getHostAddress();
                    }
                    if (address.isLinkLocalAddress() && address instanceof Inet6Address) {
                        Ipv6 = address.getHostAddress();
                    }
                }
            }
        } catch (Exception ignored) {
        }
    }

    public static String getInet6Address() {
        init();
        return Ipv6;
    }

    public static String getInet4Address() {
        init();
        return Ipv4;
    }

}

